<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理 - 智慧Agent平台</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');

        /* Agent管理特定样式 */
.agent-card {
    transition: all 0.2s ease;
}

.agent-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.knowledge-base-tag {
    display: inline-flex;
    align-items: center;
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
    border-radius: 0.25rem;
    background-color: #EFF6FF;
    color: #1E40AF;
    margin-right: 0.5rem;
    margin-bottom: 0.5rem;
}

.knowledge-base-tag i {
    margin-right: 0.25rem;
}
        body {
            font-family: 'Noto Sans SC', sans-serif;
            background: #f8fafc;
        }

        .sidebar {
            transition: all 0.3s;
        }

        .content-area {
            transition: all 0.3s;
        }

        .dashboard-card {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

        .wave-bg {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            overflow: hidden;
            line-height: 0;
            z-index: -1;
        }

        .wave-bg svg {
            position: relative;
            display: block;
            width: calc(100% + 1.3px);
            height: 150px;
        }

        .wave-bg .shape-fill {
            fill: #FFFFFF;
        }
    </style>
</head>
<body class="min-h-screen flex">
    <!-- 侧边栏导航 -->
    <div class="sidebar bg-white w-64 min-h-screen border-r border-gray-200 flex flex-col">
        <div class="p-4 border-b border-gray-200">
            <div class="flex items-center space-x-3">
                <div class="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center">
                    <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path>
                    </svg>
                </div>
                <h1 class="text-xl font-bold text-gray-800">智慧Agent平台</h1>
            </div>
        </div>

            <!-- 添加返回首页按钮 -->
    <a href="/" class="mt-4 flex items-center px-3 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900 group">
        <i class="fas fa-home mr-3 text-gray-400 group-hover:text-gray-500"></i>
        返回首页
    </a>

        <div class="flex-1 overflow-y-auto">
            <nav class="p-4 space-y-1">
                <div class="mb-4">
                    <h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wider">管理</h3>
                </div>

                <a href="#dashboard" class="flex items-center px-3 py-2 text-sm font-medium rounded-md bg-blue-50 text-blue-700 group">
                    <i class="fas fa-tachometer-alt mr-3 text-blue-600"></i>
                    控制面板
                </a>

                <a href="#users" class="flex items-center px-3 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900 group">
                    <i class="fas fa-users mr-3 text-gray-400 group-hover:text-gray-500"></i>
                    用户管理
                </a>

                 <a href="#agents" class="flex items-center px-3 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900 group">
                    <i class="fas fa-robot mr-3 text-gray-400 group-hover:text-gray-500"></i>
                    Agent管理
                </a>

                <a href="#models" class="flex items-center px-3 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900 group">
                    <i class="fas fa-brain mr-3 text-gray-400 group-hover:text-gray-500"></i>
                    模型管理
                </a>

                <!-- 在导航菜单中添加知识库管理链接 -->
                <a href="#knowledge_bases" class="flex items-center px-3 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900 group">
                    <i class="fas fa-book mr-3 text-gray-400 group-hover:text-gray-500"></i>
                    知识库管理
                </a>

                <a href="#documents" class="flex items-center px-3 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900 group">
                    <i class="fas fa-file-alt mr-3 text-gray-400 group-hover:text-gray-500"></i>
                    文档管理
                </a>

                <div class="mb-4 mt-8">
                    <h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wider">设置</h3>
                </div>

                <a href="#password" class="flex items-center px-3 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900 group">
                    <i class="fas fa-key mr-3 text-gray-400 group-hover:text-gray-500"></i>
                    修改密码
                </a>

                <a href="#settings" class="flex items-center px-3 py-2 text-sm font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900 group">
                    <i class="fas fa-cog mr-3 text-gray-400 group-hover:text-gray-500"></i>
                    系统设置
                </a>
            </nav>
        </div>

        <div class="p-4 border-t border-gray-200">
            <div class="flex items-center">
                <div class="flex-shrink-0">
                    <img id="user-avatar" class="h-10 w-10 rounded-full" src="https://ui-avatars.com/api/?name=Admin&background=2563eb&color=fff" alt="用户头像">
                </div>
                <div class="ml-3">
                    <p id="username-display" class="text-sm font-medium text-gray-700">管理员</p>
                    <button id="logout-btn" class="text-xs font-medium text-blue-600 hover:text-blue-500">退出登录</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="content-area flex-1 overflow-y-auto">
        <div class="p-8">
            <!-- 控制面板 -->
            <div id="dashboard-section" class="section-content">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-800">控制面板</h2>
                    <div class="text-sm text-gray-500">最后登录: <span id="last-login">刚刚</span></div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                    <div class="bg-white rounded-lg shadow-sm dashboard-card p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-gray-500">用户总数</p>
                                <p id="total-users" class="text-2xl font-semibold text-gray-800 mt-1">0</p>
                            </div>
                            <div class="p-3 rounded-full bg-blue-50 text-blue-600">
                                <i class="fas fa-users"></i>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white rounded-lg shadow-sm dashboard-card p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-gray-500">活跃模型</p>
                                <p id="active-models" class="text-2xl font-semibold text-gray-800 mt-1">0</p>
                            </div>
                            <div class="p-3 rounded-full bg-green-50 text-green-600">
                                <i class="fas fa-robot"></i>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white rounded-lg shadow-sm dashboard-card p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-gray-500">文档数量</p>
                                <p id="total-docs" class="text-2xl font-semibold text-gray-800 mt-1">0</p>
                            </div>
                            <div class="p-3 rounded-full bg-purple-50 text-purple-600">
                                <i class="fas fa-file-alt"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-sm dashboard-card p-6 mb-8">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-medium text-gray-800">最近活动</h3>
                        <a href="#" class="text-sm text-blue-600 hover:text-blue-500">查看全部</a>
                    </div>
                    <div class="space-y-4">
                        <div class="flex items-start">
                            <div class="flex-shrink-0 pt-0.5">
                                <div class="h-10 w-10 rounded-full bg-blue-50 text-blue-600 flex items-center justify-center">
                                    <i class="fas fa-user-plus"></i>
                                </div>
                            </div>
                            <div class="ml-3 flex-1">
                                <p class="text-sm font-medium text-gray-800">新用户注册</p>
                                <p class="text-sm text-gray-500">用户 "testuser" 刚刚注册了账户</p>
                                <p class="text-xs text-gray-400 mt-1">2分钟前</p>
                            </div>
                        </div>

                        <div class="flex items-start">
                            <div class="flex-shrink-0 pt-0.5">
                                <div class="h-10 w-10 rounded-full bg-green-50 text-green-600 flex items-center justify-center">
                                    <i class="fas fa-robot"></i>
                                </div>
                            </div>
                            <div class="ml-3 flex-1">
                                <p class="text-sm font-medium text-gray-800">模型更新</p>
                                <p class="text-sm text-gray-500">模型 "GPT-4" 配置已更新</p>
                                <p class="text-xs text-gray-400 mt-1">15分钟前</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 用户管理 -->
            <div id="users-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-800">用户管理</h2>
                    <button id="add-user-btn" class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <i class="fas fa-plus mr-2"></i>添加用户
                    </button>
                </div>

                <div class="bg-white rounded-lg shadow-sm dashboard-card overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户ID</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">用户名</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">管理员</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最后登录</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody id="users-table-body" class="bg-white divide-y divide-gray-200">
                                <!-- 用户数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 添加/编辑用户模态框 -->
            <div id="user-modal" class="fixed inset-0 z-50 hidden overflow-y-auto">
                <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                    <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                        <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
                    </div>

                    <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

                    <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                        <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                            <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4" id="modal-title">添加新用户</h3>

                            <form id="user-form">
                                <input type="hidden" id="edit-user-id">
                                <div class="mb-4">
                                    <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                                    <input type="text" id="username" name="username" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                </div>

                                <div class="mb-4">
                                    <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                                    <input type="password" id="password" name="password" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                </div>

                                <div class="mb-4">
                                    <div class="flex items-center">
                                        <input id="is-admin" name="is-admin" type="checkbox" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                                        <label for="is-admin" class="ml-2 block text-sm text-gray-700">管理员权限</label>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                            <button type="button" id="save-user-btn" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                                保存
                            </button>
                            <button type="button" id="cancel-user-btn" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                                取消
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 模型管理 -->
            <div id="models-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-800">模型管理</h2>
                    <button id="add-model-btn" class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <i class="fas fa-plus mr-2"></i>添加模型
                    </button>
                </div>

                <div class="bg-white rounded-lg shadow-sm dashboard-card overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">模型ID</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">提供商</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody id="models-table-body" class="bg-white divide-y divide-gray-200">
                                <!-- 模型数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 添加/编辑模型模态框 -->
            <div id="model-modal" class="fixed inset-0 z-50 hidden overflow-y-auto">
                <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                    <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                        <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
                    </div>

                    <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

                    <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                        <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                            <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4" id="model-modal-title">添加新模型</h3>

                            <form id="model-form">
                                <input type="hidden" id="edit-model-id">
                                <div class="mb-4">
                                    <label for="model-name" class="block text-sm font-medium text-gray-700 mb-1">模型名称</label>
                                    <input type="text" id="model-name" name="model-name" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                </div>

                                <div class="mb-4">
                                    <label for="model-type" class="block text-sm font-medium text-gray-700 mb-1">模型类型</label>
                                    <input type="text" id="model-type" name="model-type" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                </div>

                                <div class="mb-4">
                                    <label for="api-endpoint" class="block text-sm font-medium text-gray-700 mb-1">API端点</label>
                                    <input type="text" id="api-endpoint" name="api-endpoint" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                </div>

                                <div class="mb-4">
                                    <label for="api-key" class="block text-sm font-medium text-gray-700 mb-1">API密钥</label>
                                    <input type="text" id="api-key" name="api-key" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                </div>

                                <div class="mb-4">
                                    <label for="provider" class="block text-sm font-medium text-gray-700 mb-1">提供商</label>
                                    <input type="text" id="provider" name="provider" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                </div>

                                <div class="mb-4">
                                    <label for="max-tokens" class="block text-sm font-medium text-gray-700 mb-1">最大Token数</label>
                                    <input type="number" id="max-tokens" name="max-tokens" value="8192" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                </div>

                                <div class="mb-4">
                                    <label for="description" class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                                    <textarea id="description" name="description" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></textarea>
                                </div>

                                <div class="flex items-center mb-4">
                                    <input id="is-active" name="is-active" type="checkbox" checked class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                                    <label for="is-active" class="ml-2 block text-sm text-gray-700">激活状态</label>
                                </div>

                                <div class="flex items-center mb-4">
                                    <input id="supports-functions" name="supports-functions" type="checkbox" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                                    <label for="supports-functions" class="ml-2 block text-sm text-gray-700">支持函数调用</label>
                                </div>
                            </form>
                        </div>
                        <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                            <button type="button" id="save-model-btn" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                                保存
                            </button>
                            <button type="button" id="cancel-model-btn" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                                取消
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 知识库管理 -->
<div id="knowledge_bases-section" class="section-content hidden">
    <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold text-gray-800">知识库管理</h2>
        <button id="add-kb-btn" class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
            <i class="fas fa-plus mr-2"></i>添加知识库
        </button>
    </div>

    <div class="bg-white rounded-lg shadow-sm dashboard-card overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">知识库ID</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">嵌入模型</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建者</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">文档数</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody id="kb-table-body" class="bg-white divide-y divide-gray-200">
                    <!-- 知识库数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 添加/编辑知识库模态框 -->
<div id="kb-modal" class="fixed inset-0 z-50 hidden overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>

        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4" id="kb-modal-title">添加新知识库</h3>

                <form id="kb-form">
                    <input type="hidden" id="edit-kb-id">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="mb-4">
                            <label for="kb-name" class="block text-sm font-medium text-gray-700 mb-1">名称</label>
                            <input type="text" id="kb-name" name="kb-name" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="mb-4">
                            <label for="embedding-model" class="block text-sm font-medium text-gray-700 mb-1">嵌入模型</label>
                            <select id="embedding-model" name="embedding-model" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                <!-- 嵌入模型选项将通过JavaScript动态加载 -->
                            </select>
                        </div>

                        <div class="mb-4">
                            <label for="chunk-size" class="block text-sm font-medium text-gray-700 mb-1">分块大小</label>
                            <input type="number" id="chunk-size" name="chunk-size" min="100" max="2000" value="512" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="mb-4">
                            <label for="chunk-overlap" class="block text-sm font-medium text-gray-700 mb-1">分块重叠</label>
                            <input type="number" id="chunk-overlap" name="chunk-overlap" min="0" max="500" value="50" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>
                    </div>

                    <div class="mb-4">
                        <label for="kb-description" class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                        <textarea id="kb-description" name="kb-description" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></textarea>
                    </div>

                    <div class="mb-4 flex items-center">
                        <input id="kb-is-public" name="kb-is-public" type="checkbox" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                        <label for="kb-is-public" class="ml-2 block text-sm text-gray-700">公开知识库</label>
                    </div>
                </form>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" id="save-kb-btn" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                    保存
                </button>
                <button type="button" id="cancel-kb-btn" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    取消
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 知识库文档管理模态框 -->
<div id="kb-docs-modal" class="fixed inset-0 z-50 hidden overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>

        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4" id="kb-docs-modal-title">知识库文档管理</h3>

                <div class="flex justify-between items-center mb-4">
                    <h4 id="kb-docs-name" class="text-md font-medium text-gray-700"></h4>
                    <button id="upload-kb-doc-btn" class="px-3 py-1 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <i class="fas fa-upload mr-1"></i>上传文档
                    </button>
                </div>

                <div class="bg-white rounded-lg shadow-sm overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">文件名</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">大小</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">上传时间</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody id="kb-docs-table-body" class="bg-white divide-y divide-gray-200">
                                <!-- 知识库文档数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" id="close-kb-docs-btn" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                    关闭
                </button>
            </div>
        </div>
    </div>
</div>

            <!-- 文档管理 -->
            <div id="documents-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-800">文档管理</h2>
                    <button id="upload-doc-btn" class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                        <i class="fas fa-upload mr-2"></i>上传文档
                    </button>
                </div>

                <div class="bg-white rounded-lg shadow-sm dashboard-card overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">文件名</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">大小</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">上传时间</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody id="docs-table-body" class="bg-white divide-y divide-gray-200">
                                <!-- 文档数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 上传文档模态框 -->
            <div id="upload-modal" class="fixed inset-0 z-50 hidden overflow-y-auto">
                <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
                    <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                        <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
                    </div>

                    <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

                    <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                        <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                            <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">上传文档</h3>

                            <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                                <div class="space-y-1 text-center">
                                    <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
                                        <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                                    </svg>
                                    <div class="flex text-sm text-gray-600">
                                        <label for="file-upload" class="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-blue-500">
                                            <span>选择文件</span>
                                            <input id="file-upload" name="file-upload" type="file" class="sr-only">
                                        </label>
                                        <p class="pl-1">或拖放文件到此处</p>
                                    </div>
                                    <p class="text-xs text-gray-500">支持PDF, DOCX, TXT等格式</p>
                                </div>
                            </div>
                        </div>
                        <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                            <button type="button" id="upload-submit-btn" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                                上传
                            </button>
                            <button type="button" id="cancel-upload-btn" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                                取消
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Agent管理 -->
<div id="agents-section" class="section-content hidden">
    <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold text-gray-800">Agent管理</h2>
        <button id="add-agent-btn" class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
            <i class="fas fa-plus mr-2"></i>添加Agent
        </button>
    </div>

    <div class="bg-white rounded-lg shadow-sm dashboard-card overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Agent ID</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">模型</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建者</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody id="agents-table-body" class="bg-white divide-y divide-gray-200">
                    <!-- Agent数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 添加/编辑Agent模态框 -->
<div id="agent-modal" class="fixed inset-0 z-50 hidden overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>

        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4" id="agent-modal-title">添加新Agent</h3>

                <form id="agent-form">
                    <input type="hidden" id="edit-agent-id">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="mb-4">
                            <label for="agent-name" class="block text-sm font-medium text-gray-700 mb-1">名称</label>
                            <input type="text" id="agent-name" name="agent-name" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="mb-4">
                            <label for="llm-model" class="block text-sm font-medium text-gray-700 mb-1">LLM模型</label>
                            <select id="llm-model" name="llm-model" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                <!-- 模型选项将通过JavaScript动态加载 -->
                            </select>
                        </div>

                        <div class="mb-4">
                            <label for="greeting-message" class="block text-sm font-medium text-gray-700 mb-1">欢迎消息</label>
                            <input type="text" id="greeting-message" name="greeting-message" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500" value="你好，我是AI助理，有什么可以帮您？">
                        </div>

                        <div class="mb-4">
                            <label for="temperature" class="block text-sm font-medium text-gray-700 mb-1">Temperature</label>
                            <input type="number" id="temperature" name="temperature" min="0" max="2" step="0.1" value="0.7" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="mb-4">
                            <label for="max-tokens" class="block text-sm font-medium text-gray-700 mb-1">最大Token数</label>
                            <input type="number" id="max-tokens" name="max-tokens" min="1" value="2048" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="mb-4 flex items-center">
                            <input id="is-active" name="is-active" type="checkbox" checked class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="is-active" class="ml-2 block text-sm text-gray-700">激活状态</label>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label for="system-prompt" class="block text-sm font-medium text-gray-700 mb-1">系统提示</label>
                        <textarea id="system-prompt" name="system-prompt" rows="4" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"></textarea>
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">关联知识库</label>
                        <div id="knowledge-bases-container" class="space-y-2">
                            <!-- 知识库选择将通过JavaScript动态加载 -->
                        </div>
                    </div>
                </form>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" id="save-agent-btn" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                    保存
                </button>
                <button type="button" id="cancel-agent-btn" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    取消
                </button>
            </div>
        </div>
    </div>
</div>
            <!-- 修改密码 -->
            <div id="password-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-800">修改密码</h2>
                </div>

                <div class="bg-white rounded-lg shadow-sm dashboard-card p-6 max-w-2xl">
                    <form id="password-form">
                        <div class="mb-4">
                            <label for="current-password" class="block text-sm font-medium text-gray-700 mb-1">当前密码</label>
                            <input type="password" id="current-password" name="current-password" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="mb-4">
                            <label for="new-password" class="block text-sm font-medium text-gray-700 mb-1">新密码</label>
                            <input type="password" id="new-password" name="new-password" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="mb-6">
                            <label for="confirm-password" class="block text-sm font-medium text-gray-700 mb-1">确认新密码</label>
                            <input type="password" id="confirm-password" name="confirm-password" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="flex justify-end">
                            <button type="submit" class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                保存更改
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 系统设置 -->
            <div id="settings-section" class="section-content hidden">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold text-gray-800">系统设置</h2>
                </div>

                <div class="bg-white rounded-lg shadow-sm dashboard-card p-6 max-w-2xl">
                    <form id="settings-form">
                        <div class="mb-4">
                            <label for="system-name" class="block text-sm font-medium text-gray-700 mb-1">系统名称</label>
                            <input type="text" id="system-name" name="system-name" value="智慧Agent平台" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="mb-4">
                            <label for="doc-store-path" class="block text-sm font-medium text-gray-700 mb-1">文档存储路径</label>
                            <input type="text" id="doc-store-path" name="doc-store-path" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="mb-4">
                            <label for="vector-db-path" class="block text-sm font-medium text-gray-700 mb-1">向量数据库路径</label>
                            <input type="text" id="vector-db-path" name="vector-db-path" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                        </div>

                        <div class="mb-4">
                            <label for="default-model" class="block text-sm font-medium text-gray-700 mb-1">默认模型</label>
                            <select id="default-model" name="default-model" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
                                <option value="1">GPT-4</option>
                                <option value="2">DeepSeek</option>
                            </select>
                        </div>

                        <div class="flex justify-end">
                            <button type="submit" class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                保存设置
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>



    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 检查登录状态
            const token = localStorage.getItem('access_token');
                if (!token) {
                window.location.href = '/login';
                return;
                }

                    // 获取当前用户信息
        fetchCurrentUser();

        // 导航菜单点击事件
        document.querySelectorAll('nav a').forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const target = this.getAttribute('href').substring(1);
                showSection(target);
            });
        });

        // 默认显示控制面板
        showSection('dashboard');

        // 登出按钮事件
        document.getElementById('logout-btn').addEventListener('click', function() {
            logout();
        });

        // 用户管理相关事件
        document.getElementById('add-user-btn').addEventListener('click', function() {
            showUserModal('add');
        });

        document.getElementById('save-user-btn').addEventListener('click', function() {
            saveUser();
        });

        document.getElementById('cancel-user-btn').addEventListener('click', function() {
            hideUserModal();
        });

        // 模型管理相关事件
        document.getElementById('add-model-btn').addEventListener('click', function() {
            showModelModal('add');
        });

        document.getElementById('save-model-btn').addEventListener('click', function() {
            saveModel();
        });

        document.getElementById('cancel-model-btn').addEventListener('click', function() {
            hideModelModal();
        });

        // 文档管理相关事件
        document.getElementById('upload-doc-btn').addEventListener('click', function() {
            showUploadModal();
        });

        document.getElementById('upload-submit-btn').addEventListener('click', function() {
            uploadDocument();
        });

        document.getElementById('cancel-upload-btn').addEventListener('click', function() {
            hideUploadModal();
        });

        // 修改密码表单提交
        document.getElementById('password-form').addEventListener('submit', function(e) {
            e.preventDefault();
            changePassword();
        });

        // 系统设置表单提交
        document.getElementById('settings-form').addEventListener('submit', function(e) {
            e.preventDefault();
            saveSettings();
        });

        // 加载初始数据
        loadDashboardData();
        loadUsers();
        loadModels();
        loadDocuments();
    });

    // 显示指定区域内容
    function showSection(sectionId) {
        document.querySelectorAll('.section-content').forEach(section => {
            section.classList.add('hidden');
        });
        document.getElementById(`${sectionId}-section`).classList.remove('hidden');

        // 更新导航菜单活动状态
        document.querySelectorAll('nav a').forEach(link => {
            const target = link.getAttribute('href').substring(1);
            if (target === sectionId) {
                link.classList.add('bg-blue-50', 'text-blue-700');
                link.classList.remove('text-gray-600', 'hover:bg-gray-50', 'hover:text-gray-900');
            } else {
                link.classList.remove('bg-blue-50', 'text-blue-700');
                link.classList.add('text-gray-600', 'hover:bg-gray-50', 'hover:text-gray-900');
            }
        });
    }

    // 获取当前用户信息
    async function fetchCurrentUser() {
        try {
            const response = await fetch('/api/current_user', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });

            if (response.ok) {
                const data = await response.json();
                document.getElementById('username-display').textContent = data.username;
                document.getElementById('user-avatar').src = `https://ui-avatars.com/api/?name=${encodeURIComponent(data.username)}&background=2563eb&color=fff`;

                // 如果不是管理员，隐藏管理相关功能
                if (!data.is_admin) {
                    document.querySelector('a[href="#users"]').style.display = 'none';
                    document.querySelector('a[href="#models"]').style.display = 'none';
                    document.querySelector('a[href="#documents"]').style.display = 'none';
                }
            } else {
                throw new Error('获取用户信息失败');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('获取用户信息失败，请重新登录');
            logout();
        }
    }

    // 登出
    async function logout() {
        try {
            await fetch('/api/logout', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });
        } catch (error) {
            console.error('登出错误:', error);
        } finally {
            localStorage.removeItem('access_token');
            localStorage.removeItem('user_data');
            window.location.href = '/login';
        }
    }

    // 加载控制面板数据
    async function loadDashboardData() {
        try {
            // 获取用户总数
            const usersResponse = await fetch('/api/users', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });
            if (usersResponse.ok) {
                const usersData = await usersResponse.json();
                document.getElementById('total-users').textContent = usersData.length;
            }

            // 获取活跃模型数
            const modelsResponse = await fetch('/api/get_all_llm_models', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });
            if (modelsResponse.ok) {
                const modelsData = await modelsResponse.json();
                const activeModels = modelsData.filter(model => model.is_active);
                document.getElementById('active-models').textContent = activeModels.length;
            }

            // 获取文档数量
            const docsResponse = await fetch('/api/documents', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });
            if (docsResponse.ok) {
                const docsData = await docsResponse.json();
                document.getElementById('total-docs').textContent = docsData.length;
            }
        } catch (error) {
            console.error('加载控制面板数据错误:', error);
        }
    }

    // 用户管理功能
    async function loadUsers() {
        try {
            const response = await fetch('/api/users', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });

            if (response.ok) {
                const users = await response.json();
                const tableBody = document.getElementById('users-table-body');
                tableBody.innerHTML = '';

                users.forEach(user => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.user_id}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${user.username}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            ${user.is_admin ? '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">是</span>' : '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">否</span>'}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${user.last_login || '从未登录'}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <button onclick="editUser('${user.user_id}')" class="text-blue-600 hover:text-blue-900 mr-3">编辑</button>
                            <button onclick="deleteUser('${user.user_id}')" class="text-red-600 hover:text-red-900">删除</button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            }
        } catch (error) {
            console.error('加载用户列表错误:', error);
        }
    }

    function showUserModal(action, userId = null) {
        const modal = document.getElementById('user-modal');
        const title = document.getElementById('modal-title');

        if (action === 'add') {
            title.textContent = '添加新用户';
            document.getElementById('edit-user-id').value = '';
            document.getElementById('username').value = '';
            document.getElementById('password').value = '';
            document.getElementById('is-admin').checked = false;
        } else if (action === 'edit') {
            title.textContent = '编辑用户';
            // 这里应该加载用户数据，但为了简化示例，我们假设已经加载
        }

        modal.classList.remove('hidden');
    }

    function hideUserModal() {
        document.getElementById('user-modal').classList.add('hidden');
    }

    async function saveUser() {
        const userId = document.getElementById('edit-user-id').value;
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const isAdmin = document.getElementById('is-admin').checked;

        try {
            let url = '/api/register';
            let method = 'POST';

            if (userId) {
                // 更新用户逻辑 - 需要后端API支持
                url = `/api/users/${userId}`;
                method = 'PUT';
            }

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                },
                body: JSON.stringify({
                    username: username,
                    password: password,
                    is_admin: isAdmin
                })
            });

            if (response.ok) {
                alert('用户保存成功');
                hideUserModal();
                loadUsers();
            } else {
                const errorData = await response.json();
                throw new Error(errorData.error || '保存用户失败');
            }
        } catch (error) {
            console.error('保存用户错误:', error);
            alert(error.message);
        }
    }

    async function deleteUser(userId) {
        if (!confirm('确定要删除这个用户吗？此操作不可撤销。')) {
            return;
        }

        try {
            const response = await fetch(`/api/users/${userId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });

            if (response.ok) {
                alert('用户删除成功');
                loadUsers();
            } else {
                throw new Error('删除用户失败');
            }
        } catch (error) {
            console.error('删除用户错误:', error);
            alert(error.message);
        }
    }

    // 模型管理功能
    async function loadModels() {
        try {
            const response = await fetch('/api/get_all_llm_models', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });

            if (response.ok) {
                const models = await response.json();
                const tableBody = document.getElementById('models-table-body');
                tableBody.innerHTML = '';

                models.forEach(model => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${model.model_id}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${model.name}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${model.model_type}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${model.provider || 'N/A'}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            ${model.is_active ? '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">活跃</span>' : '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">未激活</span>'}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <button onclick="editModel('${model.model_id}')" class="text-blue-600 hover:text-blue-900 mr-3">编辑</button>
                            <button onclick="deleteModel('${model.model_id}')" class="text-red-600 hover:text-red-900">删除</button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            }
        } catch (error) {
            console.error('加载模型列表错误:', error);
        }
    }

    function showModelModal(action, modelId = null) {
        const modal = document.getElementById('model-modal');
        const title = document.getElementById('model-modal-title');

        if (action === 'add') {
            title.textContent = '添加新模型';
            document.getElementById('edit-model-id').value = '';
            document.getElementById('model-name').value = '';
            document.getElementById('model-type').value = '';
            document.getElementById('api-endpoint').value = '';
            document.getElementById('api-key').value = '';
            document.getElementById('provider').value = '';
            document.getElementById('max-tokens').value = '8192';
            document.getElementById('description').value = '';
            document.getElementById('is-active').checked = true;
            document.getElementById('supports-functions').checked = false;
        } else if (action === 'edit') {
            title.textContent = '编辑模型';
            // 这里应该加载模型数据，但为了简化示例，我们假设已经加载
        }

        modal.classList.remove('hidden');
    }

    function hideModelModal() {
        document.getElementById('model-modal').classList.add('hidden');
    }

    async function saveModel() {
        const modelId = document.getElementById('edit-model-id').value;
        const modelData = {
            name: document.getElementById('model-name').value,
            model_type: document.getElementById('model-type').value,
            api_endpoint: document.getElementById('api-endpoint').value,
            api_key: document.getElementById('api-key').value,
            provider: document.getElementById('provider').value,
            max_tokens: parseInt(document.getElementById('max-tokens').value),
            description: document.getElementById('description').value,
            is_active: document.getElementById('is-active').checked,
            supports_functions: document.getElementById('supports-functions').checked
        };

        try {
            let url = '/api/llm_models';
            let method = 'POST';

            if (modelId) {
                url = `/api/llm_models/${modelId}`;
                method = 'PUT';
            }

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                },
                body: JSON.stringify(modelData)
            });

            if (response.ok) {
                alert('模型保存成功');
                hideModelModal();
                loadModels();
            } else {
                const errorData = await response.json();
                throw new Error(errorData.error || '保存模型失败');
            }
        } catch (error) {
            console.error('保存模型错误:', error);
            alert(error.message);
        }
    }

    async function deleteModel(modelId) {
        if (!confirm('确定要删除这个模型吗？此操作不可撤销。')) {
            return;
        }

        try {
            const response = await fetch(`/api/llm_models/${modelId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });

            if (response.ok) {
                alert('模型删除成功');
                loadModels();
            } else {
                throw new Error('删除模型失败');
            }
        } catch (error) {
            console.error('删除模型错误:', error);
            alert(error.message);
        }
    }

    // 文档管理功能
    async function loadDocuments() {
        try {
            const response = await fetch('/api/documents', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });

            if (response.ok) {
                const documents = await response.json();
                const tableBody = document.getElementById('docs-table-body');
                tableBody.innerHTML = '';

                documents.forEach(doc => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${doc.id}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${doc.file_name}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${doc.file_type}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatFileSize(doc.file_size)}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(doc.created_at).toLocaleString()}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <button onclick="viewDocument('${doc.id}')" class="text-blue-600 hover:text-blue-900 mr-3">查看</button>
                            <button onclick="deleteDocument('${doc.id}')" class="text-red-600 hover:text-red-900">删除</button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            }
        } catch (error) {
            console.error('加载文档列表错误:', error);
        }
    }

    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    function showUploadModal() {
        document.getElementById('upload-modal').classList.remove('hidden');
    }

    function hideUploadModal() {
        document.getElementById('upload-modal').classList.add('hidden');
    }

    async function uploadDocument() {
        const fileInput = document.getElementById('file-upload');
        if (!fileInput.files || fileInput.files.length === 0) {
            alert('请选择要上传的文件');
            return;
        }

        const formData = new FormData();
        formData.append('file', fileInput.files[0]);

        try {
            const response = await fetch('/api/upload', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                },
                body: formData
            });

            if (response.ok) {
                alert('文档上传成功');
                hideUploadModal();
                loadDocuments();
                loadDashboardData(); // 更新文档计数
            } else {
                const errorData = await response.json();
                throw new Error(errorData.error || '上传文档失败');
            }
        } catch (error) {
            console.error('上传文档错误:', error);
            alert(error.message);
        }
    }

    async function deleteDocument(docId) {
        if (!confirm('确定要删除这个文档吗？此操作不可撤销。')) {
            return;
        }

        try {
            const response = await fetch(`/api/documents/${docId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });

            if (response.ok) {
                alert('文档删除成功');
                loadDocuments();
                loadDashboardData(); // 更新文档计数
            } else {
                throw new Error('删除文档失败');
            }
        } catch (error) {
            console.error('删除文档错误:', error);
            alert(error.message);
        }
    }

    // 修改密码
    async function changePassword() {
        const currentPassword = document.getElementById('current-password').value;
        const newPassword = document.getElementById('new-password').value;
        const confirmPassword = document.getElementById('confirm-password').value;

        if (newPassword !== confirmPassword) {
            alert('新密码和确认密码不匹配');
            return;
        }

        try {
            const response = await fetch('/api/change_password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                },
                body: JSON.stringify({
                    current_password: currentPassword,
                    new_password: newPassword
                })
            });

            if (response.ok) {
                alert('密码修改成功');
                document.getElementById('password-form').reset();
            } else {
                const errorData = await response.json();
                throw new Error(errorData.error || '修改密码失败');
            }
        } catch (error) {
            console.error('修改密码错误:', error);
            alert(error.message);
        }
    }

    // 保存系统设置
    async function saveSettings() {
        const settings = {
            system_name: document.getElementById('system-name').value,
            doc_store_path: document.getElementById('doc-store-path').value,
            vector_db_path: document.getElementById('vector-db-path').value,
            default_model: document.getElementById('default-model').value
        };

        try {
            const response = await fetch('/api/settings', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                },
                body: JSON.stringify(settings)
            });

            if (response.ok) {
                alert('系统设置保存成功');
            } else {
                const errorData = await response.json();
                throw new Error(errorData.error || '保存设置失败');
            }
        } catch (error) {
            console.error('保存设置错误:', error);
            alert(error.message);
        }
    }

    // 全局函数供按钮调用
    window.editUser = function(userId) {
        // 这里应该加载用户数据并显示编辑模态框
        // 为简化示例，我们只显示模态框
        showUserModal('edit', userId);
    };

    window.deleteUser = deleteUser;

    window.editModel = async function(modelId) {
    try {
        const response = await fetch(`/api/llm_models/${modelId}`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const modelData = await response.json();
            showModelModal('edit', modelId);
            // 填充表单数据
            populateModelForm(modelData);
        } else {
            throw new Error('获取模型数据失败');
        }
    } catch (error) {
        console.error('编辑模型错误:', error);
        alert(error.message);
    }
    };

    function populateModelForm(modelData) {
    document.getElementById('edit-model-id').value = modelData.model_id;
    document.getElementById('model-name').value = modelData.name;
    document.getElementById('model-type').value = modelData.model_type;
    document.getElementById('api-endpoint').value = modelData.api_endpoint;
    document.getElementById('api-key').value = modelData.api_key || '';
    document.getElementById('provider').value = modelData.provider || '';
    document.getElementById('max-tokens').value = modelData.max_tokens || '8192';
    document.getElementById('description').value = modelData.description || '';
    document.getElementById('is-active').checked = modelData.is_active || false;
    document.getElementById('supports-functions').checked = modelData.supports_functions || false;
}

    window.deleteModel = deleteModel;

    window.viewDocument = function(docId) {
        alert('查看文档功能: ' + docId);
        // 实际实现中，这里应该打开一个查看文档的模态框或页面
    };

    window.deleteDocument = deleteDocument;
// 在loadDashboardData函数中添加知识库计数

// 在页面加载时加载知识库列表
loadKnowledgeBases();
    // Agent管理功能
async function loadAgents() {
    try {
        const response = await fetch('/api/agents', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const agents = await response.json();
            const tableBody = document.getElementById('agents-table-body');
            tableBody.innerHTML = '';

            agents.forEach(agent => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${agent.agent_id}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${agent.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${agent.llm_model_name || 'N/A'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${agent.creator_name || 'N/A'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        ${agent.is_active ? '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">活跃</span>' : '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">未激活</span>'}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button onclick="editAgent('${agent.agent_id}')" class="text-blue-600 hover:text-blue-900 mr-3">编辑</button>
                        <button onclick="deleteAgent('${agent.agent_id}')" class="text-red-600 hover:text-red-900">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }
    } catch (error) {
        console.error('加载Agent列表错误:', error);
    }
}

function showAgentModal(action, agentId = null) {
    const modal = document.getElementById('agent-modal');
    const title = document.getElementById('agent-modal-title');

    if (action === 'add') {
        title.textContent = '添加新Agent';
        document.getElementById('edit-agent-id').value = '';
        document.getElementById('agent-name').value = '';
        document.getElementById('greeting-message').value = '你好，我是AI助理，有什么可以帮您？';
        document.getElementById('temperature').value = '0.7';
        document.getElementById('max-tokens').value = '2048';
        document.getElementById('system-prompt').value = '';
        document.getElementById('is-active').checked = true;

        // 加载模型选项
        loadModelOptions();
        // 加载知识库选项
        loadKnowledgeBaseOptions();
    } else if (action === 'edit') {
        title.textContent = '编辑Agent';
        // 这里会通过editAgent函数加载具体数据
    }

    modal.classList.remove('hidden');
}

function hideAgentModal() {
    document.getElementById('agent-modal').classList.add('hidden');
}

async function loadModelOptions() {
    try {
        const response = await fetch('/api/get_all_llm_models', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const models = await response.json();
            const select = document.getElementById('llm-model');
            select.innerHTML = '';

            models.forEach(model => {
                if (model.is_active) {
                    const option = document.createElement('option');
                    option.value = model.model_id;
                    option.textContent = `${model.name} (${model.provider || '未知提供商'})`;
                    select.appendChild(option);
                }
            });
        }
    } catch (error) {
        console.error('加载模型选项错误:', error);
    }
}

async function loadKnowledgeBaseOptions() {
    try {
        const response = await fetch('/api/knowledge_bases', { // 假设您有获取知识库的API
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const knowledgeBases = await response.json();
            const container = document.getElementById('knowledge-bases-container');
            container.innerHTML = '';

            knowledgeBases.forEach(kb => {
                const div = document.createElement('div');
                div.className = 'flex items-center';
                div.innerHTML = `
                    <input id="kb-${kb.kb_id}" name="knowledge_bases" type="checkbox" value="${kb.kb_id}" class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                    <label for="kb-${kb.kb_id}" class="ml-2 block text-sm text-gray-700">${kb.name}</label>
                `;
                container.appendChild(div);
            });
        }
    } catch (error) {
        console.error('加载知识库选项错误:', error);
    }
}

async function saveAgent() {
    const agentId = document.getElementById('edit-agent-id').value;
    const agentData = {
        name: document.getElementById('agent-name').value,
        llm_model_id: document.getElementById('llm-model').value,
        greeting_message: document.getElementById('greeting-message').value,
        system_prompt: document.getElementById('system-prompt').value,
        temperature: parseFloat(document.getElementById('temperature').value),
        max_tokens: parseInt(document.getElementById('max-tokens').value),
        is_active: document.getElementById('is-active').checked
    };

    // 获取选中的知识库
    const selectedKBs = [];
    document.querySelectorAll('input[name="knowledge_bases"]:checked').forEach(cb => {
        selectedKBs.push(cb.value);
    });

    try {
        let url = '/api/agents';
        let method = 'POST';

        if (agentId) {
            url = `/api/agents/${agentId}`;
            method = 'PUT';
        }

        // 首先保存Agent基本信息
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            },
            body: JSON.stringify(agentData)
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '保存Agent失败');
        }

        const agentResponse = await response.json();
        const savedAgentId = agentResponse.agent?.agent_id || agentId;

        // 然后处理知识库关联
        if (savedAgentId) {
            // 先获取当前关联的知识库
            const currentKBResponse = await fetch(`/api/agents/${savedAgentId}`, {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                }
            });

            if (currentKBResponse.ok) {
                const agentInfo = await currentKBResponse.json();
                const currentKBs = agentInfo.knowledge_bases.map(kb => kb.kb_id);

                // 需要添加的知识库
                const toAdd = selectedKBs.filter(kb => !currentKBs.includes(kb));
                // 需要移除的知识库
                const toRemove = currentKBs.filter(kb => !selectedKBs.includes(kb));

                // 添加新的关联
                for (const kbId of toAdd) {
                    await fetch(`/api/agents/${savedAgentId}/knowledge_bases`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                        },
                        body: JSON.stringify({ kb_id: kbId })
                    });
                }

                // 移除不再关联的知识库
                for (const kbId of toRemove) {
                    await fetch(`/api/agents/${savedAgentId}/knowledge_bases/${kbId}`, {
                        method: 'DELETE',
                        headers: {
                            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                        }
                    });
                }
            }
        }

        alert('Agent保存成功');
        hideAgentModal();
        loadAgents();
    } catch (error) {
        console.error('保存Agent错误:', error);
        alert(error.message);
    }
}

async function deleteAgent(agentId) {
    if (!confirm('确定要删除这个Agent吗？此操作不可撤销。')) {
        return;
    }

    try {
        const response = await fetch(`/api/agents/${agentId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            alert('Agent删除成功');
            loadAgents();
        } else {
            throw new Error('删除Agent失败');
        }
    } catch (error) {
        console.error('删除Agent错误:', error);
        alert(error.message);
    }
}

async function editAgent(agentId) {
    try {
        const response = await fetch(`/api/agents/${agentId}`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const agentData = await response.json();
            showAgentModal('edit', agentId);

            // 填充表单数据
            document.getElementById('edit-agent-id').value = agentData.agent_id;
            document.getElementById('agent-name').value = agentData.name;
            document.getElementById('api-key').value = agentData.api_key;
            document.getElementById('greeting-message').value = agentData.greeting_message;
            document.getElementById('temperature').value = agentData.temperature;
            document.getElementById('max-tokens').value = agentData.max_tokens;
            document.getElementById('system-prompt').value = agentData.system_prompt || '';
            document.getElementById('is-active').checked = agentData.is_active;

            // 加载模型选项并设置选中值
            await loadModelOptions();
            document.getElementById('llm-model').value = agentData.llm_model_id;

            // 加载知识库选项并设置选中状态
            await loadKnowledgeBaseOptions();
            agentData.knowledge_bases.forEach(kb => {
                const checkbox = document.getElementById(`kb-${kb.kb_id}`);
                if (checkbox) {
                    checkbox.checked = true;
                }
            });
        } else {
            throw new Error('获取Agent数据失败');
        }
    } catch (error) {
        console.error('编辑Agent错误:', error);
        alert(error.message);
    }
}

// 在DOMContentLoaded事件监听器中添加以下代码
document.getElementById('add-agent-btn').addEventListener('click', function() {
    showAgentModal('add');
});

document.getElementById('save-agent-btn').addEventListener('click', function() {
    saveAgent();
});

document.getElementById('cancel-agent-btn').addEventListener('click', function() {
    hideAgentModal();
});


// 加载Agent列表
loadAgents();

// 在loadDashboardData函数中添加Agent计数
async function loadDashboardData() {
    try {
        // ... 其他代码 ...

        // 获取Agent数量
        const agentsResponse = await fetch('/api/agents', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });
        if (agentsResponse.ok) {
            const agentsData = await agentsResponse.json();
            // 在控制面板的某个卡片中显示Agent数量
            // 您可能需要添加一个新的卡片来显示这个数据
        }
    } catch (error) {
        console.error('加载控制面板数据错误:', error);
    }
}

// 在页面加载时加载Agent列表
loadAgents();

// 全局函数供按钮调用
window.editAgent = editAgent;
window.deleteAgent = deleteAgent;

// 知识库管理功能
async function loadKnowledgeBases() {
    try {
        const response = await fetch('/api/knowledge_bases', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const knowledgeBases = await response.json();
            const tableBody = document.getElementById('kb-table-body');
            tableBody.innerHTML = '';

            knowledgeBases.forEach(kb => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${kb.kb_id}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${kb.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${kb.embedding_model_name || 'N/A'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${kb.creator_name || 'N/A'}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${kb.documents_count}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        ${kb.is_public ? '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">公开</span>' : '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">私有</span>'}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button onclick="editKnowledgeBase('${kb.kb_id}')" class="text-blue-600 hover:text-blue-900 mr-3">编辑</button>
                        <button onclick="manageKbDocuments('${kb.kb_id}', '${kb.name}')" class="text-indigo-600 hover:text-indigo-900 mr-3">文档</button>
                        <button onclick="deleteKnowledgeBase('${kb.kb_id}')" class="text-red-600 hover:text-red-900">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }
    } catch (error) {
        console.error('加载知识库列表错误:', error);
    }
}

function showKbModal(action, kbId = null) {
    const modal = document.getElementById('kb-modal');
    const title = document.getElementById('kb-modal-title');

    if (action === 'add') {
        title.textContent = '添加新知识库';
        document.getElementById('edit-kb-id').value = '';
        document.getElementById('kb-name').value = '';
        document.getElementById('kb-description').value = '';
        document.getElementById('chunk-size').value = '512';
        document.getElementById('chunk-overlap').value = '50';
        document.getElementById('kb-is-public').checked = false;

        // 加载嵌入模型选项
        loadEmbeddingModelOptions();
    } else if (action === 'edit') {
        title.textContent = '编辑知识库';
        // 这里会通过editKnowledgeBase函数加载具体数据
    }

    modal.classList.remove('hidden');
}

function hideKbModal() {
    document.getElementById('kb-modal').classList.add('hidden');
}

async function loadEmbeddingModelOptions() {
    try {
        const response = await fetch('/api/get_all_llm_models', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const models = await response.json();
            const select = document.getElementById('embedding-model');
            select.innerHTML = '';

            // 过滤出嵌入模型
            const embeddingModels = models.filter(model => model.model_type === 'embedding' && model.is_active);

            embeddingModels.forEach(model => {
                const option = document.createElement('option');
                option.value = model.model_id;
                option.textContent = `${model.name} (${model.provider || '未知提供商'})`;
                select.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载嵌入模型选项错误:', error);
    }
}

async function saveKnowledgeBase() {
    const kbId = document.getElementById('edit-kb-id').value;
    const kbData = {
        name: document.getElementById('kb-name').value,
        embedding_model_id: document.getElementById('embedding-model').value,
        description: document.getElementById('kb-description').value,
        chunk_size: parseInt(document.getElementById('chunk-size').value),
        chunk_overlap: parseInt(document.getElementById('chunk-overlap').value),
        is_public: document.getElementById('kb-is-public').checked
    };

    try {
        let url = '/api/knowledge_bases';
        let method = 'POST';

        if (kbId) {
            url = `/api/knowledge_bases/${kbId}`;
            method = 'PUT';
        }

        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            },
            body: JSON.stringify(kbData)
        });

        if (response.ok) {
            alert('知识库保存成功');
            hideKbModal();
            loadKnowledgeBases();
        } else {
            const errorData = await response.json();
            throw new Error(errorData.error || '保存知识库失败');
        }
    } catch (error) {
        console.error('保存知识库错误:', error);
        alert(error.message);
    }
}

async function deleteKnowledgeBase(kbId) {
    if (!confirm('确定要删除这个知识库吗？此操作将删除所有关联的文档和向量数据，且不可撤销。')) {
        return;
    }

    try {
        const response = await fetch(`/api/knowledge_bases/${kbId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            alert('知识库删除成功');
            loadKnowledgeBases();
        } else {
            const errorData = await response.json();
            if (errorData.error && errorData.error.includes('linked to agents')) {
                alert('无法删除知识库：该知识库已被Agent关联。请先解除关联后再试。');
            } else {
                throw new Error('删除知识库失败');
            }
        }
    } catch (error) {
        console.error('删除知识库错误:', error);
        alert(error.message);
    }
}

async function editKnowledgeBase(kbId) {
    try {
        const response = await fetch(`/api/knowledge_bases/${kbId}`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const kbData = await response.json();
            showKbModal('edit', kbId);

            // 填充表单数据
            document.getElementById('edit-kb-id').value = kbData.kb_id;
            document.getElementById('kb-name').value = kbData.name;
            document.getElementById('kb-description').value = kbData.description || '';
            document.getElementById('chunk-size').value = kbData.chunk_size || 512;
            document.getElementById('chunk-overlap').value = kbData.chunk_overlap || 50;
            document.getElementById('kb-is-public').checked = kbData.is_public || false;

            // 加载嵌入模型选项并设置选中值
            await loadEmbeddingModelOptions();
            document.getElementById('embedding-model').value = kbData.embedding_model_id;
        } else {
            throw new Error('获取知识库数据失败');
        }
    } catch (error) {
        console.error('编辑知识库错误:', error);
        alert(error.message);
    }
}

function showKbDocsModal(kbId, kbName) {
    const modal = document.getElementById('kb-docs-modal');
    document.getElementById('kb-docs-modal-title').textContent = `知识库文档管理 - ${kbName}`;
    document.getElementById('kb-docs-name').textContent = kbName;
    document.getElementById('kb-docs-modal').setAttribute('data-kb-id', kbId);

    loadKbDocuments(kbId);
    modal.classList.remove('hidden');
}

function hideKbDocsModal() {
    document.getElementById('kb-docs-modal').classList.add('hidden');
}

async function loadKbDocuments(kbId) {
    try {
        const response = await fetch(`/api/knowledge_bases/${kbId}/documents`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            const documents = await response.json();
            const tableBody = document.getElementById('kb-docs-table-body');
            tableBody.innerHTML = '';

            documents.forEach(doc => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${doc.file_name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${doc.file_type}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formatFileSize(doc.file_size)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(doc.created_at).toLocaleString()}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button onclick="viewKbDocument('${kbId}', '${doc.doc_id}')" class="text-blue-600 hover:text-blue-900 mr-3">查看</button>
                        <button onclick="deleteKbDocument('${kbId}', '${doc.doc_id}')" class="text-red-600 hover:text-red-900">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }
    } catch (error) {
        console.error('加载知识库文档错误:', error);
    }
}

async function uploadKbDocument() {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';

    fileInput.onchange = async (e) => {
        const file = e.target.files[0];
        if (!file) return;

        const kbId = document.getElementById('kb-docs-modal').getAttribute('data-kb-id');
        const formData = new FormData();
        formData.append('file', file);

        try {
            const response = await fetch(`/api/knowledge_bases/${kbId}/upload`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
                },
                body: formData
            });

            if (response.ok) {
                alert('文档上传成功');
                loadKbDocuments(kbId);
            } else {
                const errorData = await response.json();
                throw new Error(errorData.error || '上传文档失败');
            }
        } catch (error) {
            console.error('上传知识库文档错误:', error);
            alert(error.message);
        }
    };

    fileInput.click();
}

async function deleteKbDocument(kbId, docId) {
    if (!confirm('确定要删除这个文档吗？此操作将从知识库中永久移除该文档及其向量数据。')) {
        return;
    }

    try {
        const response = await fetch(`/api/knowledge_bases/${kbId}/documents/${docId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('access_token')}`
            }
        });

        if (response.ok) {
            alert('文档删除成功');
            loadKbDocuments(kbId);
        } else {
            throw new Error('删除文档失败');
        }
    } catch (error) {
        console.error('删除知识库文档错误:', error);
        alert(error.message);
    }
}

// 在DOMContentLoaded事件监听器中添加以下代码
document.getElementById('add-kb-btn').addEventListener('click', function() {
    showKbModal('add');
});

document.getElementById('save-kb-btn').addEventListener('click', function() {
    saveKnowledgeBase();
});

document.getElementById('cancel-kb-btn').addEventListener('click', function() {
    hideKbModal();
});

document.getElementById('upload-kb-doc-btn').addEventListener('click', function() {
    uploadKbDocument();
});

document.getElementById('close-kb-docs-btn').addEventListener('click', function() {
    hideKbDocsModal();
});

// 加载知识库列表
loadKnowledgeBases();

// 全局函数供按钮调用
window.editKnowledgeBase = editKnowledgeBase;
window.deleteKnowledgeBase = deleteKnowledgeBase;
window.manageKbDocuments = function(kbId, kbName) {
    showKbDocsModal(kbId, kbName);
};
window.viewKbDocument = function(kbId, docId) {
    alert('查看文档功能: ' + docId + ' 在知识库: ' + kbId);
    // 实际实现中，这里应该打开一个查看文档的模态框或页面
};
window.deleteKbDocument = deleteKbDocument;

</script>
</body>
</html>